#!/usr/bin/env python

""" 
Daemon script that runs as background/daemon/service application to handle 
recording video to disk and also stream to the network using Gstreamer.

Configuration is loaded from C{/etc/opencircuit/opencircuit.conf} at run-time.
"""

import sys, os

APPNAME = 'opencircuit'
LOGFILE = '/var/log/%s.log' % APPNAME

def main_loop():
    """ 
    Test main loop.
    """
    import time
    while True: time.sleep(10)
    return
        

if __name__ == '__main__':
    
    # fork child process
    try:
        pid = os.fork()
        # for testing
        #f = open('/tmp/opencircuit.pid', 'w', 0)
        #f.write('pid: %d\n' % pid)
        #f.close()
        if pid > 0: sys.exit(0)
    except OSError, e:
        sys.stderr.write(
            '%s: failed to fork child process: %s (Errno: %d)\n' % 
            (APPNAME, e.strerror, e.errno))
    
    # change file mode mask
    os.umask(0)
    
    # open log file
    with open(LOGFILE, 'a') as LOG:

        # create a unique session id
        try:
            os.setsid()
        except OSError, e:
            LOG.write(
                '[%s] %s: failed to set a unique session ID: %s (Errno: %d)\n' %
                (time.ctime(), APPNAME, e.strerror, e.errno))
        
        ## change to a known to be existent directory
        try:
            os.chdir('/')
        except OSError, e:
            LOG.write(
                '[%s] %s: failed to change to change dir to "/": %s (Errno: %d)\n' %
                (time.ctime(), APPNAME, e.strerror, e.errno))
        
    # close standard file descriptors
    os.close(0)
    os.close(1)
    os.close(2)
    
    main_loop()
    
    
    
    
    
    
    
    
    
    

    
